﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ComponentModel;
using System.Collections.Concurrent;
using System.ServiceModel.Activation;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net;
using System.Web;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using OpenQA.Selenium.Firefox;

namespace AlimamaPublish
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class RestService : IRestService
    {
        static CookieContainer myCookieContainer;
        //static IWebDriver driver = new ChromeDriver();
        static IWebDriver driver = new FirefoxDriver();
        static string token;
        static bool needReLogin = false;

        public string GetUrl(string url)
        {
            string result = null;
            try
            {
                result = doGet(myCookieContainer, token, url);
                if(result == null)
                {
                    lock (driver)
                    {
                        if (needReLogin)
                        {
                            driver.Quit();
                            driver = new FirefoxDriver();
                            login();
                            needReLogin = false;
                        }
                    }
                    return doGet(myCookieContainer, token, url);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return result;
        }

        private void login()
        {
            myCookieContainer = new CookieContainer();
            try
            {
                foreach (OpenQA.Selenium.Cookie cookie in openBrowser())
                {
                    if (cookie.Name.Equals("_tb_token_"))
                        token = cookie.Value;
                    System.Net.Cookie ck = new System.Net.Cookie(cookie.Name, cookie.Value);
                    ck.Domain = "alimama.com";//必须写对
                    myCookieContainer.Add(ck);
                }
                driver.Navigate().GoToUrl("http://pub.alimama.com/myunion.htm#!/promo/self/links");
                doPost(myCookieContainer, token);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                driver.Quit();
                driver = new FirefoxDriver();
            }
        }


        private ReadOnlyCollection<OpenQA.Selenium.Cookie> openBrowser()
        {
            string baseURL = "http://www.alimama.com/member/login.htm?forward=http%3A%2F%2Fpub.alimama.com%2F#!/promo/self/linkshttp://www.baidu.com/";
            driver.Navigate().GoToUrl(baseURL);
            driver.SwitchTo().Frame(driver.FindElement(By.Name("taobaoLoginIfr")));
            driver.FindElement(By.Id("TPL_username_1")).Clear();
            driver.FindElement(By.Id("TPL_username_1")).SendKeys("yehan2004");

            IWebElement element = driver.FindElement(By.Id("J_SafeLoginCheck"));
            if (element.Selected)
                element.Click();

            driver.FindElement(By.Id("TPL_password_1")).Clear();
            driver.FindElement(By.Id("TPL_password_1")).SendKeys("yuki015314");
            driver.FindElement(By.Id("J_SubmitStatic")).Click();
            IJavaScriptExecutor je = (IJavaScriptExecutor)driver;
            string docstate = (string)je.ExecuteScript("return document.readyState");

            //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            //wait.Until<bool>((d) =>
            //{
            //    return docstate.Equals("complete");
            //});
            Thread.Sleep(5000);
            ReadOnlyCollection<OpenQA.Selenium.Cookie> cookies = driver.Manage().Cookies.AllCookies;
            return cookies;
        }

        private int doPost(CookieContainer myCookieContainer, string token)
        {
            HttpWebRequest hreq = (HttpWebRequest)HttpWebRequest.Create("http://pub.alimama.com/common/adzone/selfAdzoneCreate.json");
            hreq.Method = "POST";
            hreq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            hreq.Accept = "application/json, text/javascript, */*; q=0.01";

            //自己创建的CookieContainer
            hreq.CookieContainer = myCookieContainer;

            string postdata = "promotion_type=29#29&gcid=8&siteid=7560186&selectact=sel&adzoneid=25416295&_tb_token_=" + token;
            byte[] byte1 = Encoding.ASCII.GetBytes(postdata);
            hreq.ContentLength = byte1.Length;

            Stream poststream = hreq.GetRequestStream();
            poststream.Write(byte1, 0, byte1.Length);
            poststream.Close();

            HttpWebResponse hres = (HttpWebResponse)hreq.GetResponse();

            if (hres.StatusCode == HttpStatusCode.OK)
                if (hres.ResponseUri.AbsoluteUri.StartsWith("http://www.alimama.com/member/login.htm"))
                    return 1;
                else if (hres.ResponseUri.AbsoluteUri.Equals("http://pub.alimama.com/common/adzone/selfAdzoneCreate.json"))
                    return 0;
            return 2;
        }

        private string doGet(CookieContainer myCookieContainer, string token, string originurl)
        {
            string usrurl = HttpUtility.UrlEncode(originurl);
            StringBuilder url = new StringBuilder("http://pub.alimama.com/urltrans/urltrans.json?siteid=7560186&adzoneid=25416295&promotionURL=" + usrurl + "&t=" + GetTime());
            url.Append("&_tb_token_=" + token + "&_input_charset=utf-8");

            HttpWebRequest hreq = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
            hreq.Method = "GET";
            hreq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            hreq.Accept = "application/json, text/javascript, */*; q=0.01";
            hreq.Timeout = 2000;
            //自己创建的CookieContainer
            hreq.CookieContainer = myCookieContainer;
            HttpWebResponse hres = null;
            try
            {
                hres = (HttpWebResponse)hreq.GetResponse();
            }catch(Exception e)
            {
                needReLogin = true;
                return null;
            }
            if (hres.ResponseUri.AbsoluteUri.StartsWith("http://www.alimama.com/member/login.htm"))
            {
                needReLogin = true;
                return null;
            }
            byte[] byte2 = new byte[hres.ContentLength];

            hres.GetResponseStream().Read(byte2, 0, (int)hres.ContentLength);
            string resultdata = Encoding.ASCII.GetString(byte2);
            return getClickUrl(resultdata);
        }

        public string GetName()
        {
            return "Kaede";
        }

        public string GetTime()
        {
            Int64 retval = 0;
            DateTime st = new DateTime(1970, 1, 1);
            TimeSpan t = (DateTime.Now.ToUniversalTime() - st);
            retval = (Int64)(t.TotalMilliseconds + 0.5);
            return retval.ToString();
        }

        private string getClickUrl(string json)
        {
            JObject oText = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader(json)));
            return oText["data"]["sclick"].ToString();
        }
    }
}
